package com.jic.product.controller.manage;

import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.conf.request.ProductCommentRequest;
import com.jic.conf.response.ProductCommentResponse;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import com.jic.product.constant.consist.ResponseCode;
import com.jic.product.exception.AppRuntimeException;
import com.jic.product.model.entity.File;
import com.jic.product.model.entity.ProductComment;
import com.jic.product.service.FileService;
import com.jic.product.service.ProductCommentService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("all")
@Slf4j
@RestController
@RequestMapping("/productComment")
public class ProductCommentController  {

    @Autowired
    private ProductCommentService productCommentService;
    @Autowired
    private FileService fileService;
    @Resource
    private ProductListApi productListApi;

    @ApiOperation("商品评论分页查询")
    @PostMapping("/getProductCommentPage")
    public RestResult<PageResult<ProductCommentResponse>> getProductCommentPage(@RequestBody ProductCommentRequest productCommentRequest) {
        try {
            Page page = new Page();
            page.setLimit(productCommentRequest.getLimit());
            page.setStart(productCommentRequest.getStart());
            ProductComment productComment = new ProductComment();
            BeanUtils.copyProperties(productCommentRequest,productComment);
            PageResult<ProductComment> productCommentPageResult = productCommentService.queryPage(productComment, page);
            List<ProductComment> productCommentResponses = productCommentPageResult.getRows();
            List<ProductCommentResponse> res = new ArrayList<>();
            productCommentResponses.forEach(productCommentResponse -> {
                //查询图片
                List<File> fileList = fileService.query(new File() {{
                    setType(0);
                    setBusinessId(productCommentResponse.getId());
                }});
                ProductCommentResponse productCommentResponse1 = new ProductCommentResponse();
                try {
                    BeanUtils.copyProperties(productCommentResponse,productCommentResponse1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                productCommentResponse1.setFileList(fileList);
                res.add(productCommentResponse1);
            });
            if (productCommentRequest.getType() != null && productCommentRequest.getType() != 0 &&  productCommentRequest.getType() == 2){
                return RestResult.success(new PageResult<ProductCommentResponse>(){{
                    setTotal(productCommentPageResult.getTotal());
                    setRows(res);
                }});
            }
            List<ProductCommentResponse> resultList = new ArrayList<>();
            for (ProductCommentResponse sysProvinceCity : res) {
                if(sysProvinceCity == null){
                    continue;
                }
                if (sysProvinceCity.getPid()!= null && sysProvinceCity.getPid() == 0 && sysProvinceCity.getType() == 1) {
                    if (!exists(resultList, sysProvinceCity)) {
                        resultList.add(sysProvinceCity);
                    }
                }
            }
            findChildren(resultList, res);
            return RestResult.success(new PageResult<ProductCommentResponse>(){{
                setRows(resultList);
                setTotal(productCommentPageResult.getTotal());
            }});
        }catch (Exception e){
            log.error("商品评论分页查询异常",e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "商品评论分页查询异常");
        }
    }


    @ApiOperation("商品评论详情查询")
    @PostMapping("/getProductCommentInfo")
    public RestResult<ProductCommentResponse> getProductCommentInfo(@RequestBody ProductCommentRequest productCommentRequest) {
        try {
            long id = productCommentRequest.getId();
            if (id == 0){
                throw  new Exception("必传参数为空 id");
            }
            ProductComment productComment = productCommentService.queryByPrimaryKey(id);
            ProductCommentResponse productCommentResponse = new ProductCommentResponse();
            BeanUtils.copyProperties(productComment,productCommentResponse);
            //TODO 查询分类
            RestResult<ProductAfterInfoByIdResponse> productAfterInfoByIdResponseRestResult = productListApi.queryProductInfoById(productCommentResponse.getProductId());
            if(StringUtils.isNotEmpty(productAfterInfoByIdResponseRestResult.getData().getChineseName())){
                productCommentResponse.setProductCode(productAfterInfoByIdResponseRestResult.getData().getChineseName());
            }
            if(StringUtils.isNotEmpty(productAfterInfoByIdResponseRestResult.getData().getFullNamePath())){
                productCommentResponse.setProductType(productAfterInfoByIdResponseRestResult.getData().getFullNamePath());
            }
            List<File> fileList = fileService.query(new File() {{
                setType(0);
                setBusinessId(productCommentResponse.getId());
            }});
            productCommentResponse.setFileList(fileList);
            return RestResult.success(productCommentResponse);
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @ApiOperation("商品评论编辑")
    @PostMapping("/updateProductComment")
    public RestResult<String> updateProductComment(@RequestBody ProductCommentRequest productCommentRequest) {
        try {
            ProductComment productComment = new ProductComment();
            BeanUtils.copyProperties(productCommentRequest,productComment);
            if (productComment.getId() == 0) throw new Exception("修改商品评论出错 ===>>> 必传参数为空");
            productCommentService.update(productComment);
            return RestResult.success("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @PostMapping("stickProductComment")
    @ResponseBody
    public RestResult<String> stickProductComment(@RequestBody ProductCommentRequest productCommentRequest){
        long id = productCommentRequest.getId();
        if (id == 0){
            return RestResult.error("9999","必传参数为0");
        }
        ProductComment productComment = productCommentService.queryByPrimaryKey(id);
        long productId = productComment.getProductId();
        List<ProductComment> productCommentList = productCommentService.query(new ProductComment() {{
            setProductId(productId);
        }});
        productCommentList.forEach(productCommentVo -> {
            productCommentService.update(new ProductComment(){{
                setId(productCommentVo.getId());
                setStickyStatus(0);
            }});
        });
        productCommentService.update(new ProductComment(){{
            setId(id);
            setStickyStatus(1);
        }});
        return RestResult.success("成功");
    }


    /**
     * 判断当前权限是否添加过
     *
     * @param sysMenus
     * @param sysMenu
     * @return
     */
    private boolean exists(List<ProductCommentResponse> sysMenus, ProductCommentResponse sysMenu) {
        boolean exist = false;
        for (ProductCommentResponse menu : sysMenus) {
            if (menu.getId() == sysMenu.getId()) {
                exist = true;
            }
        }
        return exist;
    }

    private void  findChildren(List<ProductCommentResponse> SysMenus, List<ProductCommentResponse> menus) throws Exception {
        for (ProductCommentResponse SysMenu : SysMenus) {
            List<ProductCommentResponse> children = new ArrayList<>();
            for (ProductCommentResponse menu : menus) {
//                if (menuType == 1 && menu.getAsInteger("type") == 2) {
//                    // 如果是获取类型不需要按钮，且菜单类型是按钮的，直接过滤掉
//                    continue;
//                }
                if (menu == null) {
                    continue;
                }
                if(menu.getPid()!=null){
                if (SysMenu.getId() == (menu.getPid())) {

//                    SysMenuVo sysMenuVo = (SysMenuVo) StrongParentSubclass.parentSubclass(menu, new SysMenuVo());
                    if (!exists(children, menu)) {
                        children.add(menu);
                    }
                }
            }
            }
            SysMenu.setChildren(children);
//            children.sort((o1, o2) -> o1.getSort().compareTo(o2.getSort()));
            findChildren(children, menus);
        }
    }

}
